﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using Pixysoft.Framework.Configurations;
using Pixysoft.Framework.Verifications;
using System.Xml.Serialization;

namespace Pixysoft.Framework.Noebe.MemoryCaches.Core
{
    class ShallowCacheDataRow : ICacheDataRow
    {
        string cacheKey;
        DateTime createDate;
        DateTime endDate;
        int hitRate;
        protected List<CacheDataRowCell> cells = new List<CacheDataRowCell>();

        protected ShallowCacheDataRow()
        {
        }

        public ShallowCacheDataRow(string cacheKey, int timespan, DataRow datarow)
        {
            this.cacheKey = cacheKey;

            this.CreateDate = Pixysoft.Tools.GlobalTimer.Instance.GetGlobalTime();

            if (timespan < 0)
                this.EndDate = DateTime.MaxValue;
            else
                this.EndDate = this.CreateDate.AddMilliseconds(timespan);

            this.hitRate = 0;

            foreach (DataColumn col in datarow.Table.Columns)
            {
                CacheDataRowCell cell = new CacheDataRowCell(
                    col.ColumnName, datarow[col]);

                cells.Add(cell);
            }
        }

        [XmlAttribute("cachekey")]
        public string CacheKey
        {
            get { return cacheKey; }
            set { cacheKey = value; }
        }

        [XmlAttribute("createdate")]
        public DateTime CreateDate
        {
            get { return createDate; }
            set { createDate = value; }
        }

        [XmlAttribute("enddate")]
        public DateTime EndDate
        {
            get { return endDate; }
            set { endDate = value; }
        }

        [XmlAttribute("hitrate")]
        public int HitRate
        {
            get { return hitRate; }
            set { hitRate = value; }
        }

        public void Hit()
        {
            hitRate++;
        }

        public void GetDataRow(System.Data.DataTable table)
        {
            DataRow row = table.NewRow();
            foreach (CacheDataRowCell cell in cells)
            {
                if (!table.Columns.Contains(cell.ColumnName))
                    throw Exceptions.UnexpectedResultException("return table do not contain the column name in cache row. table:{0},column:{1}",
                        table.TableName, cell.ColumnName);

                try
                {
                    row[cell.ColumnName] = cell.GetColumnValue();
                }
                catch (Exception ex)
                {
                    row[cell.ColumnName] = DBNull.Value;

                    LoggerHelper.Fatal(ex);
                }
            }
            table.Rows.Add(row);
        }
    }
}
